<template>
  <div class="app-container task-progress">
    <Pagetitle
      :title="pageTitle.title"
      :name="pageTitle.name"
      :btnName="pageTitle.btnName"
      @btnFun="btnFun"
    ></Pagetitle>
    <div class="filter-container">

    </div>
    <div class="table-container">
      <Tabs
        v-model="tabTaskStatus"
        @on-click="getApprovalProgress()"
      >
        <TabPane
          label="全部"
          name=""
        >
        </TabPane>
        <TabPane
          label="待审批"
          name="1"
        >
        </TabPane>
        <TabPane
          label="已通过"
          name="3"
        >
        </TabPane>
        <TabPane
          label="已拒绝"
          name="5"
        >
        </TabPane>
      </Tabs>

      <Table
        stripe
        :loading="dataTable.loading"
        :border="dataTable.border"
        :columns="dataTable.columns"
        :data="dataTable.data"
      >

      </Table>

      <Row class="mtop20">
        <Col
          :md="4"
          class="flex-start-center height-30 page"
        >
        <div>
          共{{count}}条
          <Select
            v-model="limit"
            size="small"
            class="lz-select-width"
            @on-change="changePageSize(1)"
          >
            <Option
              v-for="item in pageSizeSeletc"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
        </div>
        </Col>
        <Col
          :md="12"
          class="flex-center-center height-30"
        >
        <Page
          v-if="pageshow"
          :total="count"
          :page-size="limit"
          @on-change="changePageSize"
          size="small"
          show-elevator
        />
        </Col>
      </Row>
    </div>
    <Modal
      v-model="urlsModal"
      :closable="false"
      :footer-hide="true"
    >
      <div class="modal-content">
        <div class="modal-header">
          <span>下载文档</span>
          <a @click="closeModal()">
            <svg-icon icon-class="close" />
          </a>
        </div>
        <div class="modal-body">
          <template v-for="url in urls">
            <a
              class="url"
              :href="url.fileUrl"
              target="_blank"
            >
              {{url.fileName}}
            </a>
          </template>

        </div>
      </div>
    </Modal>
    <Modal
      v-model="updateTaskModal"
      :closable="false"
      :footer-hide="true"
    >
      <div class="modal-content">
        <Form
          ref="editorTaskForm"
          :model="editorTaskForm"
          :rules="ruleValidate"
          :label-width="80"
        >
          <div class="modal-header">
            <span>任务更改</span>
            <a @click="closeModal('editorTaskForm')">
              <svg-icon icon-class="close" />
            </a>
          </div>
          <div class="modal-body">
            <Row>
              <Col :span="12">
              <FormItem
                label="品牌"
                prop="brandId"
              >
                <Select
                  v-model="editorTaskForm.brandId"
                  placeholder="全部品牌"
                >
                  <template v-for="brand in brandListSelect">
                    <Option
                      :key="brand.brandId"
                      :value="brand.brandId"
                    >{{brand.brandName}}</Option>
                  </template>
                </Select>
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem
                label="成本中心"
                prop="costCenterId"
              >
                <Select
                  v-model="editorTaskForm.costCenterId"
                  placeholder="全部品牌"
                >
                  <template
                    v-for="brand in brandListSelect"
                    v-if="brand.brandId === editorTaskForm.brandId"
                  >
                    <template v-for="(item,index) in brand.costCenterList">
                      <Option
                        :key="item.index"
                        :value="item.id"
                      >{{item.costCenterName}}</Option>
                    </template>
                  </template>
                </Select>
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col :span="12">
              <FormItem
                label="一级物料"
                prop="firstMaterial"
              >
                <Select
                  v-model="editorTaskForm.firstMaterial"
                  placeholder="全部一级物料"
                >
                  <Option
                    v-for="(material,index) in materialListSelect"
                    :key="material.index"
                    :value="material.firstMaterial"
                  >{{material.firstMaterial}}</Option>

                </Select>
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem
                label="二级物料"
                prop="materialId"
              >
                <Select
                  v-model="editorTaskForm.materialId"
                  placeholder="全部二级物料"
                >
                  <template
                    v-for="(material,index) in materialListSelect"
                    v-if="material.firstMaterial === editorTaskForm.firstMaterial"
                  >
                    <template v-for="(item,index) in material.secondMaterialList">
                      <Option
                        :key="item.index"
                        :value="item.id"
                      >{{item.secondMaterial}}</Option>
                    </template>
                  </template>
                </Select>
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem label="物料数量">
                <Input
                  v-model="editorTaskForm.materialCount"
                  placeholder="输入数量"
                ></Input>
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem label="完成时间">
                <DatePicker
                  type="date"
                  :clearable="false"
                  placeholder="请选择月份"
                  v-model="editorTaskForm.finishTime"
                ></DatePicker>
              </FormItem>
              </Col>
              <Col :span="24">
              <FormItem label="附件">
                <!-- <Button type="primary">点击上传</Button>
                <span class="upload-tips">文件总大小不超过10MB</span>
                <div class="upload-file">
                  <span>nam1.jpg</span>
                  <span>name2.jpg</span>
                </div> -->
                <Upload
                  ref="upload"
                  multiple
                  :action="uploadUrl"
                  :before-upload="handleUpload"
                  :on-success="handleSuccess"
                  :max-size="51200"
                  :on-progress="handleProgress"
                  :on-remove="handleRemove"
                  :headers="headerUpload"
                  :show-upload-list="false"
                  name="files"
                >
                  <Button>上传文件</Button>
                </Upload>
              </FormItem>
              </Col>
              <Col :span="24">
              <FormItem>
                <template v-for="(info,infoIndex) in editorTaskForm.imgInfos">
                  <div class="pic-name">
                    {{info.name}}
                    <span
                      class="pic-loading"
                      v-if="info.status === '1'"
                    >上传中</span>
                    <span
                      class="pic-success"
                      v-if="info.status === '2'"
                    >完成</span>
                    <span
                      class="pic-close"
                      @click="handleRemove(info,infoIndex)"
                    >
                      X
                    </span>
                  </div>
                </template>
              </FormItem>
              </Col>
            </Row>
          </div>
          <div class="modal-footer">
            <Button @click="closeModal('editorTaskForm')">取消</Button>
            <Button
              type="primary"
              @click="handleSubmitUpdateTask('editorTaskForm')"
            >确定</Button>
          </div>
        </Form>
      </div>
    </Modal>

  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  fetchApprovalProgress,
  fetchDeleteTask,
  fetchUpdateMyTask,
  fetchTaskAddContent
} from "@/api/table";
import { Pagetitle } from "@/components";
import format from "date-format";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      pageshow: true,
      //总页码
      count: 0,
      //页码
      currentPage: 1,
      //总条数
      limit: 10,
      pageSizeSeletc: [
        {
          value: 10,
          label: "10条/页"
        },
        {
          value: 20,
          label: "20条/页"
        }
      ],
      dataTable: {
        loading: false,
        border: false,
        columns: [
          {
            minWidth: 100,
            title: "任务ID",
            key: "taskId"
          },
          {
            minWidth: 100,
            title: "品牌",
            key: "brandName"
          },
          {
            minWidth: 100,
            title: "成本中心",
            key: "costCenterName"
          },
          {
            minWidth: 100,
            title: "一级物料",
            key: "firstMaterialName"
          },
          {
            minWidth: 100,
            title: "二级物料",
            key: "secondMaterialName"
          },
          {
            minWidth: 100,
            title: "物料数量",
            key: "materialCount"
          },
          {
            minWidth: 100,
            title: "完成时间",
            key: "finishTime",
            render: (h, params) => {
              return h(
                "div",
                format("yyyy-MM-dd", new Date(params.row.finishTime))
              );
            }
          },
          {
            minWidth: 100,
            title: "录入时间",
            key: "createTime",
            render: (h, params) => {
              return h(
                "div",
                format("yyyy-MM-dd", new Date(params.row.createTime))
              );
            }
          },
          {
            minWidth: 100,
            title: "文档",
            key: "fileList",
            render: (h, params) => {
              if (params.row.fileList.length > 0) {
                return h(
                  "Button",
                  {
                    props: {
                      type: "text",
                      size: "small"
                    },
                    on: {
                      click: () => {
                        if (params.row.fileList.length === 1) {
                          const href = params.row.fileList[0].fileUrl;
                          window.open(href, "_blank");
                        } else {
                          this.urlsModal = true;
                        }
                        this.urls = params.row.fileList;
                      }
                    }
                  },
                  "查看"
                );
              } else {
                return h("Span", "空");
              }
            }
          },
          {
            minWidth: 100,
            title: "审核人",
            key: "auditorName"
          },
          {
            minWidth: 100,
            title: "状态",
            key: "taskStatusType",
            render: (h, params) => {
              let typeClass;
              let typeText;
              if (params.row.taskStatus === 1) {
                typeClass = "type_1";
                typeText = "待审核";
                return h(
                  "div",
                  {
                    class: typeClass
                  },
                  typeText
                );
              } else if (params.row.taskStatus === 3) {
                typeClass = "type_3";
                typeText = "已通过";
                return h(
                  "div",
                  {
                    class: typeClass
                  },
                  typeText
                );
              } else if (params.row.taskStatus === 5) {
                typeClass = "type_5";
                typeText = "已拒绝";
                return h("div", [
                  h(
                    "div",
                    {
                      class: typeClass
                    },
                    typeText
                  ),
                  h(
                    "div",
                    {
                      class: typeClass
                    },
                    "(" + params.row.description + ")"
                  )
                ]);
              }
            }
          },
          {
            minWidth: 100,
            title: "操作",
            key: "action",
            render: (h, params) => {
              if (params.row.taskStatus !== 3) {
                return h(
                  "div",
                  {
                    class: "btn-table-box"
                  },
                  [
                    h(
                      "Button",
                      {
                        props: {
                          type: "text",
                          size: "small"
                        },
                        on: {
                          click: () => {
                            this.showUpdateTaskModal(params.row);
                          }
                        }
                      },
                      "更改"
                    ),
                    h(
                      "Poptip",
                      {
                        props: {
                          confirm: true,
                          placement: "top-end",
                          title: "确定要删除吗！",
                          type: "error",
                          size: "small",
                          width: 200
                        },
                        on: {
                          "on-ok": () => {
                            this.deleteTask(params.row);
                          },
                          "on-cancel": () => {}
                        }
                      },
                      [
                        h(
                          "Button",
                          {
                            props: {
                              type: "text",
                              size: "small"
                            }
                          },
                          "删除"
                        )
                      ]
                    )
                  ]
                );
              }
            }
          }
        ],
        data: []
      },
      pageTitle: {
        title: "任务进度"
      },
      tabTaskStatus: "",
      progressList: [],
      urlsModal: false,
      urls: [],
      materialListSelect: [],
      brandListSelect: [],
      updateTaskModal: false,
      editorTaskForm: {
        taskId: "",
        finishTime: "",
        brandId: "",
        costCenterId: "",
        materialId: "",
        materialCount: "",
        imgInfos: [],
        firstMaterial: ""
      },
      canSubmitAddTasks: false,
      ruleValidate: {
        brandId: [
          {
            required: true,
            message: "选择品牌",
            trigger: "change",
            type: "number"
          }
        ],
        costCenterId: [
          {
            required: true,
            message: "选择成本中心",
            trigger: "change",
            type: "number"
          }
        ],
        firstMaterial: [
          {
            required: true,
            message: "选择一级物料",
            trigger: "change"
          }
        ],
        materialId: [
          {
            required: true,
            message: "选择二级物料",
            trigger: "change",
            type: "number"
          }
        ]
      },
      //下载
      uploadList: []
    };
  },
  components: {
    Pagetitle
  },
  mounted() {
    this.getApprovalProgress();
    this.getTaskAddContent();
  },
  methods: {
    //分页
    changePageSize(index) {
      this.currentPage = index;
      this.getApprovalProgress();
    },
    btnFun() {
      this.addBrandModal = true;
    },
    async getApprovalProgress() {
      this.dataTable.loading = true;
      let status;
      if (this.tabTaskStatus === 0) {
        status = "";
      } else {
        status = this.tabTaskStatus;
      }
      const res = await fetchApprovalProgress({
        pageNo: this.currentPage,
        pageSize: this.limit,
        userId: this.userId,
        taskStatus: status
      });
      this.dataTable.loading = false;
      this.count = res.data.total;
      this.dataTable.data = [];
      res.data.list.forEach(item => {
        const data = {};
        data.brandName = item.brandName;
        data.brandId = item.brandId;
        data.costCenterName = item.costCenterName;
        data.costCenterId = item.costCenterId;
        data.firstMaterialName = item.firstMaterialName;
        data.secondMaterialName = item.secondMaterialName;
        data.materialId = item.materialId;
        data.materialCount = item.materialCount;
        data.finishTime = item.finishTime;
        data.fileList = item.fileList;
        data.createTime = item.createTime;
        data.taskStatus = item.taskStatus;
        data.taskId = item.taskId;
        data.auditorName = item.auditorName;
        data.description = item.description;
        this.dataTable.data.push(data);
      });
    },
    async getTaskAddContent() {
      const res = await fetchTaskAddContent({
        userId: this.userId
      });
      this.brandListSelect = [];
      this.materialListSelect = [];
      res.data.brandList.forEach(item => {
        const data = {};
        data.brandName = item.brandName;
        data.brandId = item.id;
        data.costCenterList = item.costCenterList;
        this.brandListSelect.push(data);
      });
      res.data.materialList.forEach(item => {
        const data = {};
        data.firstMaterial = item.firstMaterial;
        data.secondMaterialList = item.secondMaterialList;
        this.materialListSelect.push(data);
      });
    },
    async deleteTask(row) {
      await fetchDeleteTask({
        taskId: row.taskId,
        userId: this.userId
      });
      this.$Message.success("删除成功");
      this.getApprovalProgress();
    },
    async updateMyTask(name) {
      const imgList = [];
      this.editorTaskForm.imgInfos.forEach(info => {
        if (info.url) {
          imgList.push(info.url);
        }
      });
      await fetchUpdateMyTask({
        taskId: this.editorTaskForm.taskId,
        finishTime: format("yyyy-MM-dd", this.editorTaskForm.finishTime),
        userId: this.userIds,
        brandId: this.editorTaskForm.brandId,
        costCenterId: this.editorTaskForm.costCenterId,
        materialId: this.editorTaskForm.materialId,
        materialCount: this.editorTaskForm.materialCount,
        fileUrls: imgList.toString()
      });
      this.closeModal(name);
      this.getApprovalProgress();
      this.$Message.success("修改成功");
    },
    resetForm(name) {
      this.$refs[name].resetFields();
    },
    closeModal(name) {
      if (name) {
        this.resetForm(name);
      }
      this.urlsModal = false;
      this.updateTaskModal = false;
    },
    handleSubmitUpdateTask(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.updateMyTask(name);
        }
      });
    },
    showUpdateTaskModal(info) {
      this.editorTaskForm.taskId = info.taskId;
      this.editorTaskForm.finishTime = new Date(info.finishTime);
      this.editorTaskForm.brandId = info.brandId;
      this.editorTaskForm.costCenterId = info.costCenterId;
      this.editorTaskForm.materialId = info.materialId;
      this.editorTaskForm.firstMaterial = info.firstMaterialName;
      this.editorTaskForm.materialCount = info.materialCount;
      this.updateTaskModal = true;
      this.editorTaskForm.imgInfos = [];
      info.fileList.forEach(item => {
        const data = {};
        data.name = item.fileName;
        data.url = item.fileUrl;
        data.status = "";
        this.editorTaskForm.imgInfos.push(data);
      });
    },
    handleUpload(file) {
      const imgInfo = {};
      imgInfo.name = file.name;
      imgInfo.status = "1";
      imgInfo.url = "";
      this.editorTaskForm.imgInfos.push(imgInfo);
    },
    handleProgress(event, file, fileList) {},
    handleSuccess(res, file) {
      if (res.status !== 500) {
        const newImg = res.data.url;
        const infos = this.editorTaskForm.imgInfos;
        for (let i = 0; infos.length > i; i++) {
          if (infos[i].name === file.name) {
            infos[i].status = "2";
            infos[i].url = newImg;
          }
        }
      } else {
        this.$Message.error("文件上传失败");
      }
    },
    //物料index,图片信息,图片index
    handleRemove(info, infoIndex) {
      this.editorTaskForm.imgInfos.map((item, itemIndex) => {
        if (item.name === info.name) {
          this.editorTaskForm.imgInfos.splice(itemIndex, 1);
        }
      });
    }
  },
  computed: {
    ...mapGetters(["userId"]),
    uploadUrl: () => {
      return process.env.BASE_URL + "file/upload";
    },
    headerUpload: () => {
      const data = {};
      data.token = getToken();
      return data;
    }
  }
};
</script>
<style lang="less" scoped>
@import "~@/styles/mixin";
.pic-loading {
  color: #cb2d00;
}
.pic-success {
  color: #71ce3b;
}
.pic-name {
  margin: 3px 0;
}
.pic-close {
  display: inline-block;
  margin-left: 5px;
  cursor: pointer;
}
.pic-close:hover {
  color: #cb2d00;
}
.url {
  display: block;
  margin: 0 10px;
}
.upload-tips {
  margin-left: 10px;
}
.upload-file {
  span {
    margin-right: 10px;
  }
}
</style>
<style >
.task-progress .ivu-tabs {
  overflow: visible;
}
.type_1 {
  color: #5c5959;
}
.type_3 {
  color: #cbc9c9;
}
.type_5 {
  color: #cb2d00;
}
.ivu-poptip-body {
  display: flex;
}
</style>